package com.car.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;

import com.bbs.crawl.BBSCrawlOfBitAuto;
import com.bbs.dao.BBSDaoOfBitAuto;
import com.car.util.ConnectionPool;
import com.car.util.Util;

public class Car {
	Connection conn = ConnectionPool.getConnection("carvoice_core", "root", "zhouzhou100428", "192.168.1.168");
	Connection co = ConnectionPool.getConnection("bitauto", "root", "zhouzhou100428", "192.168.1.168");

	public List<String> getTables() {
		List<String> list = new ArrayList<>();

		Statement st = null;
		ResultSet rs = null;
		String sql = "SHOW TABLES";
		try {
			st = co.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				list.add(rs.getString("Tables_in_bitauto"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public List<Integer> getIDS() {
		List<Integer> ids = new ArrayList<>();
		Connection conn = ConnectionPool.getConnection("carvoice_core", "root", "zhouzhou100428", "192.168.1.168");
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT bitauto_bbs,bitauto_bbsurl FROM core_brand_bitauto WHERE LENGTH(bitauto_bbsurl)>0 AND bitauto_bbsurl is not NULL GROUP BY(bitauto_bbsurl) ";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				ids.add(rs.getInt("bitauto_bbs"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ids;
	}

	public String id2UrlSpell(int id) {
		String res = "";
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT bitauto_bbsurl FROM core_brand_bitauto WHERE bitauto_bbs=" + id;
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			if (rs.next()) {
				res = rs.getString("bitauto_bbsurl");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}

	public static void main(String[] args) {
		Car car = new Car();
		List<String> list = car.getTables();
		List<Integer> table = new ArrayList<>();
		List<Integer> ids = car.getIDS();
		for (String s : list) {
			Matcher m = Util.getMatched(s, "(.*)(\\d{4})");
			if (m != null) {
				table.add(Integer.parseInt(m.group(2)));
			}
		}
		BBSDaoOfBitAuto bbsdao = new BBSDaoOfBitAuto();
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(35);
		for (Integer i : ids) {
			if (!(table.contains(i))) {
				String urlspell = car.id2UrlSpell(i);
				fixedThreadPool.execute(new BBSCrawlOfBitAuto(bbsdao, urlspell));
			}
		}
		fixedThreadPool.shutdown();
	}
}
